package com.xjzd.std.concurrency;

public class ThreadTerminate {

    static volatile boolean flag = true;

    public static void main1(String[] args) throws InterruptedException {
        // 1. run方法return或抛出异常
        // 2. stop（不用）强制让线程结束
        // 3. 使用共享变量，需要volatile保证变量的线程可见性

        Thread t1 = new Thread(() -> {
            while (flag) {

            }
        });
        t1.start();

        Thread.sleep(1000);
        flag = false;
    }

    public static void main(String[] args) throws InterruptedException {
        // 4. interrupt打断线程
        //     1. 使用共享变量的方式：Thread.currentThread.isInterrupted()方法。线程一直运行
        //     2. 通过打断WAITING或者TIMED_WAITING状态的线程。线程有一定的休眠时间。最常用

        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    System.out.println("t1 do task");
                    synchronized (ThreadTerminate.class) {
                        ThreadTerminate.class.wait();
                    }
                } catch (InterruptedException e) {
                    System.out.println("t1 over");
                    return;
                }
            }
        });
        t1.start();
        Thread.sleep(500);
        synchronized (ThreadTerminate.class) {
            t1.interrupt();
        }
    }
}
